package models

import (
	"time"
)

type SnippTag struct {
	TagId     int       `json:"tid,omitempty"`
	UserId    int       `json:"uid,omitempty"`
	TagName   string    `json:"tname,omitempty"`
	TagStatus int       `json:"tstatus,omitempty"`
	TagTime   time.Time `json:"ttime,omitempty"`
}
type SnippTags []*SnippTag

//获取全部标签
func (db *DB) GetAllTag() (SnippTags, error) {
	sts := make(SnippTags, 0)
	rows, err := db.Query("SELECT * FROM snipp_tag")
	checkErr(err)
	defer rows.Close()

	for rows.Next() {
		var tagTime string
		st := new(SnippTag)
		err := rows.Scan(&st.TagId, &st.UserId, &st.TagName, &st.TagStatus, &tagTime)
		checkErr(err)
		st.TagTime, _ = time.Parse("2006-01-02 15:04:05", tagTime)

		sts = append(sts, st)
	}
	checkErr(err)
	return sts, nil
}


//创建标签
func (db *DB) InsertTag(tag *SnippTag) int64 {
	stmt, err := db.Prepare("INSERT INTO `snippets_box`.`snipp_tag`(`user_id`, `tag_name`, `tag_status`, `tag_time`) VALUES (?, ?, ?, ?)")
	checkErr(err)

	res, err := stmt.Exec(tag.UserId, tag.TagName, tag.TagStatus, tag.TagTime)
	checkErr(err)

	id, err := res.LastInsertId()
	checkErr(err)

	return id
}

//更新
func (db *DB) Update(tag *SnippTag) int64 {
	//更新数据
	stmt, err := db.Prepare("UPDATE `snippets_box`.`snipp_tag` SET `user_id` = ?, `tag_name` = ?, `tag_status` = ?, `tag_time` = ? WHERE `tag_id` = ?;")
	checkErr(err)

	res, err := stmt.Exec(tag.UserId, tag.TagName, tag.TagStatus, tag.TagTime, tag.TagId)
	checkErr(err)

	affect, err := res.RowsAffected()
	checkErr(err)

	return affect
}

//删除
func (db *DB) Delete(id int64) int64 {
	//删除数据
	stmt, err := db.Prepare("delete from snippets_box where tag_id=?")
	checkErr(err)

	res, err := stmt.Exec(id)
	checkErr(err)

	affect, err := res.RowsAffected()
	checkErr(err)

	return affect
}
